import './login.html';
import { Template } from 'meteor/templating';
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import { Message } from '../../components/message/message.js'

Template.App_login.onCreated(function(){
  let self = this;
  self.direct_to_apply = new ReactiveVar(false);
  if (Meteor.userId()) {
    FlowRouter.go('/dashboard');
  }
});

Template.App_login.events({
  'submit form'(event, instance){
    event.preventDefault();



    let username_jquery = "[name='username']";
  	let password_jquery = "[name='password']";

    let username = $(username_jquery).val();
    let password = $(password_jquery).val();

    if (username == '') {
      Message.sendError("请输入用户名");
      return false;
    }
    if (password == '') {
      Message.sendError("请输入密码");
      return false;

    }
    UIBlock.block('正在登录中，请稍候');

    Meteor.loginWithPassword(username, password, function(error){
        if (error) {
               if (error.reason == "Match failed") {
               Message.sendError("密码或其他信息错误");
               UIBlock.unblock();

               return false;
              }
              if (error.reason == "Incorrect password") {
               Message.sendError("密码错误");
               UIBlock.unblock();

               return false;
              }
              if (error.reason == "User not found") {
               Message.sendError("用户不存在");
               UIBlock.unblock();

               return false;
              }

             }else{
                  Meteor.call('user.loginrecord');
                  UIBlock.block('正在登录中，请稍候');
                  if (instance.direct_to_apply.get()) {
                    instance.direct_to_apply.set(false);
                    FlowRouter.go('/dashboard');
                    Message.sendSuccess("登录成功");
                     UIBlock.unblock();
                     return false;
                  }
                 FlowRouter.go('/dashboard');
                 Message.sendSuccess("登录成功");
                  UIBlock.unblock();
             }
             Meteor.call('user.getroles', function(error,result){
              if (!error) {
                Session.set("roles", result);
              }
             });


    });

  },
  'click #login_apply'(event, instance){

    instance.direct_to_apply.set(true);
    $('form').submit();

  }
});
